package com.nbjtjc.safe.api.sys;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.crypto.SecureUtil;
import com.nbjtjc.common.validator.ValidatorUtils;
import com.nbjtjc.safe.annotation.SysLog;
import com.nbjtjc.safe.bean.Constant;
import com.nbjtjc.safe.bean.Page;
import com.nbjtjc.safe.bean.Result;
import com.nbjtjc.safe.mapper.sys.SysDeptMapper;
import com.nbjtjc.safe.mapper.sys.SysFileMapper;
import com.nbjtjc.safe.mapper.sys.SysUserMapper;
import com.nbjtjc.safe.mapper.sys.SysUserPostMapper;
import com.nbjtjc.safe.model.edu.EduCertificate;
import com.nbjtjc.safe.model.edu.EduPlanList;
import com.nbjtjc.safe.model.sys.SysDept;
import com.nbjtjc.safe.model.sys.SysFile;
import com.nbjtjc.safe.model.sys.SysUser;
import com.nbjtjc.safe.model.sys.SysUserPost;
import com.nbjtjc.safe.service.sys.SysDeptService;
import com.nbjtjc.safe.service.sys.SysFileService;
import com.nbjtjc.safe.service.sys.SysNoticeService;
import com.nbjtjc.safe.service.sys.SysUserService;
import com.nbjtjc.safe.util.MyShiroUtils;
import org.apache.catalina.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.*;

/**
 * 系统用户
 */
@RestController
@CrossOrigin("*")
public class SysUserController {

    private static Logger logger= LoggerFactory.getLogger(SysUserController.class);
    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysDeptService sysDeptService;

    @Autowired
    private SysNoticeService sysNoticeService;
    @Autowired
    private SysUserPostMapper sysUserPostMapper;

    @Autowired
    private SysDeptMapper sysDeptMapper;
    @Autowired
    private SysFileService fileService;
    @Autowired
    private SysFileMapper sysFileMapper;
    @Value("${aliyun.oss.domain}")
    private String domain;
    @RequestMapping(value = "/logout", method = RequestMethod.POST)
    public Result<Boolean> logout() {
        Result<Boolean> result = new Result<>();
        try {
            Subject subject = SecurityUtils.getSubject();
            subject.logout();
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse("登出失败");
        }
        return result;
    }


    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Object login(SysUser user, HttpServletRequest request) {
        Map<String, Object> result = new HashMap<>();
        ValidatorUtils.validateEntity(user);
        try {
            Subject subject = SecurityUtils.getSubject();
            UsernamePasswordToken token = new UsernamePasswordToken(user.getLoginName()
                    , SecureUtil.md5(user.getPassword()));
            subject.login(token);
            SysUser sessionUser = (SysUser) subject.getSession().getAttribute("user");

            SysDept sysDept = sysDeptMapper.selectByPrimaryKey(MyShiroUtils.getCompanyId());
            if (ObjectUtil.isNotNull(sysDept)&&ObjectUtil.isNotNull(sysDept.getLogoFileId())) {
                SysFile sysFile=sysFileMapper.selectByPrimaryKey(sysDept.getLogoFileId());
                if(ObjectUtil.isNotNull(sysFile))
                    sessionUser.setCompanyLogPath(domain+"/"+sysFile.getPath());
                sessionUser.setLogoFileId(sysDept.getLogoFileId());
            }
            if(sessionUser.getEnterpriseId()<=0){
                sessionUser.setParentCompanyId(sysDeptService.getParentCompanyId(MyShiroUtils.getCompanyId()));
//            sessionUser.setSysNoticePageInfo(sysNoticeService.getMyNotice(false,new Page()));
                setUserHeadFilePath(sessionUser);
                sessionUser.setUnreadNoticeCount(sysNoticeService.getUnReadNoticeCount());
                sessionUser.setPosts(sysUserPostMapper.findByUserId(sessionUser.getUserId()));
            }
            result.put("user", sessionUser);
        } catch (UnknownAccountException e) {
            result.put("message", e.getMessage());
            return result;
        } catch (IncorrectCredentialsException e) {
            result.put("message", "账号或密码不正确");
            result.put("success", false);
            return result;
        } catch (LockedAccountException e) {
            result.put("message", "账号已被锁定,请联系管理员");
            result.put("success", false);
            return result;
        } catch (AuthenticationException e) {
            e.printStackTrace();
            result.put("message", "账户验证失败");
            result.put("success", false);
            return result;
        }
        result.put("success", true);
        return result;
    }

    /**
     * 设置登录人员的头像路径
     * @param sysUser
     */
    private void setUserHeadFilePath(SysUser sysUser){
        SysFile sysFile=sysFileMapper.findUserHeadFile(sysUser.getUserId()
                ,Constant.SysFileType.HEAD_FILE.getValue());

        if(ObjectUtil.isNotNull(sysFile)){
            sysUser.setHeadPath(domain+"/"+sysFile.getPath());
        }else{
            logger.warn("该用户没有上传头像:"+sysUser.getUserId());
        }
    }

    @RequestMapping(value = "/user/find", method = {RequestMethod.GET, RequestMethod.POST})
    public Result find(SysUser sysUser, Page page) {
        Result result = new Result();
        try {
            result = sysUserService.find(sysUser, page);
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse(e.getMessage());
        }
        return result;
    }
    @RequestMapping(value = "/user/addEnterpriseUser", method = {RequestMethod.GET, RequestMethod.POST})
    public Result addEnterpriseUser(@RequestBody SysUser sysUser) {
        Result result = new Result();
        try {
            result = sysUserService.addEnterpriseUser(sysUser);
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse(e.getMessage());
        }
        return result;
    }
    @RequestMapping(value = "/user/updateEnterpriseUser", method = {RequestMethod.GET, RequestMethod.POST})
    public Result updateEnterpriseUser(@RequestBody SysUser sysUser) {
        Result result = new Result();
        try {
            result = sysUserService.updateEnterpriseUser(sysUser);
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse(e.getMessage());
        }
        return result;
    }
    @RequestMapping(value = "/user/addOrUpdate", method = {RequestMethod.GET, RequestMethod.POST})
    public Result add(SysUser sysUser) {
        Result result = new Result();
        try {
            result = sysUserService.addOrUpdate(sysUser);
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse(e.getMessage());
        }
        return result;
    }


    @PostMapping("/user/delete")
//    @RequiresPermissions("/deleteUser")
    public Result delete(SysUser sysUser) {
        Result result = new Result();
        try {
            sysUserMapper.deleteByPrimaryKey(sysUser.getUserId());
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse(e.getMessage());
        }
        return result;
    }

    @SysLog("下载人员花名册")
    @RequestMapping(value = "/user/sysUserOutput", method = {RequestMethod.GET, RequestMethod.POST})
    public Result sysUserOutput(HttpServletResponse response, SysUser sysUser) {
        Result result = new Result();

        try {
            List<SysUser> sysUsers = sysUserMapper.search(sysUser, new Page());

            result = sysUserService.sysUserOutput(response, sysUsers);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }

    @SysLog("导入人员花名册")
    @RequestMapping(value = "/user/addBatch", method = {RequestMethod.POST})
    public Result addBatch(HttpServletRequest request) {
        Result result = new Result();
        try {
            // 解析器解析request的上下文未登录或者过期
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 先判断request中是否包含mutipart类型的数据
            if (multipartResolver.isMultipart(request)) {
                // 再将request中得数据转化成multipart类型的数据f
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                List<MultipartFile> multipartFiles = multiRequest.getFiles("file");
                Iterator iterator = multiRequest.getFileNames();
                while (iterator.hasNext()) {
                    MultipartFile file = multiRequest.getFile((String) iterator.next());
                    result = sysUserService.addBatch(file);
                    if (result.isSuccess()) {
                    } else {
                        result.setFalse(result.getMessage());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse("导入失败" + e.getMessage());
        }
        return result;
    }

    @PostMapping("/user/checkWxUserExist")
    public Result wxCheckUser(String code) throws IOException {
        Result result = sysUserService.checkWxUserExist(code);
        return result;
    }

    @PostMapping("/user/bindWxUser")
    public Result bindWxUser(String loginName, String pwd, String openId) {
        Result result = sysUserService.bindWxUser(loginName, pwd, openId);
        return result;
    }

    @PostMapping("/user/uploadHead")
    public Result uploadHead(HttpServletRequest request, SysFile pic) {
        Result<List<SysFile>> result = new Result<>();
        List<SysFile> files = new ArrayList<>();
        try {
            // 解析器解析request的上下文未登录或者过期
            CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
            // 先判断request中是否包含mutipart类型的数据
            if (multipartResolver.isMultipart(request)) {
                // 再将request中得数据转化成multipart类型的数据f
                MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
                List<MultipartFile> multipartFiles = multiRequest.getFiles("file");
                Iterator iterator = multiRequest.getFileNames();
                while (iterator.hasNext()) {
                    MultipartFile file = multiRequest.getFile((String) iterator.next());
                    if (!file.isEmpty()) {
                        Result<SysFile> fileResult = fileService.uploadFile(file, pic);
                        if (fileResult.isSuccess()) {
                            int headResult=sysUserMapper.setUserHead(MyShiroUtils.getSessionUserId()
                                    , fileResult.getData().getfId());
                            if(headResult!=0){
                                logger.error("上传头像失败");
                                result.setFalse("上传头像失败");
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setFalse("上传失败" + e.getMessage());
        }
        result.setData(files);
        return result;
    }

    @PostMapping("/user/resetPassword")
    public Result resetPwd(SysUser sysUser){
        return sysUserService.resetPwd(sysUser);
    }
}
